package com.unity.bh3.netty;

import com.alibaba.fastjson2.JSON;
import com.unity.bh3.model.FriendMessage;
import com.unity.bh3.dto.UserInfoResponse;
import com.unity.bh3.service.UserService;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.HashMap;

@Component
public class WebSocketManager {
    // 用户ID -> Channel映射
    private final Map<Long, Channel> userChannels = new ConcurrentHashMap<>();

    @Autowired
    private UserService userService;

    public Map<Long, Channel> getUserChannels() {
        return userChannels;
    }

    public void addChannel(Long userId, Channel channel) {
        userChannels.put(userId, channel);
    }

    public void removeChannel(Long userId) {
        userChannels.remove(userId);
    }

    public void sendFriendRequest(Long targetUserId, Long fromUserId) {
        Channel channel = userChannels.get(targetUserId);
        if (channel != null && channel.isActive()) {
            WebSocketMessage message = WebSocketMessage.builder()
                    .type("FRIEND_REQUEST")
                    .data(fromUserId)
                    .build();
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(message)));
        }
    }
    public void sendSystemMessage(Long targetUserId, String message) {
        Channel channel = userChannels.get(targetUserId);
        if (channel != null && channel.isActive()) {
            WebSocketMessage messageObj = WebSocketMessage.builder()
                    .type("SYSTEM")
                    .data(message)
                    .build();
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(messageObj)));
        }
    }
    public void sendErrorMessage(Long targetUserId, String errorMessage) {
        Channel channel = userChannels.get(targetUserId);
        if (channel != null && channel.isActive()) {
            WebSocketMessage message = WebSocketMessage.builder()
                    .type("ERROR")
                    .data(errorMessage)
                    .build();
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(message)));
        }
    }
    public void sendFriendRequestResult(Long targetUserId, Long fromUserId, boolean accepted) {
        Channel channel = userChannels.get(targetUserId);
        if (channel != null && channel.isActive()) {
            Map<String, Object> data = new ConcurrentHashMap<>();
            data.put("userId", fromUserId);
            data.put("accepted", accepted);
            
            WebSocketMessage message = WebSocketMessage.builder()
                    .type("FRIEND_REQUEST_RESULT")
                    .data(data)
                    .build();
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(message)));
        }
    }

    public void sendFriendMessage(Long targetUserId, FriendMessage message) {
        Channel channel = userChannels.get(targetUserId);
        if (channel != null && channel.isActive()) {
            // 获取发送者信息
            UserInfoResponse senderInfo = userService.getUserInfo(message.getSenderId());
            
            Map<String, Object> messageData = new HashMap<>();
            messageData.put("id", message.getId());
            messageData.put("senderId", message.getSenderId());
            messageData.put("receiverId", message.getReceiverId());
            messageData.put("senderNickname", senderInfo.getNickname());
            messageData.put("senderLevel", senderInfo.getLevel());
            messageData.put("content", message.getContent());
            messageData.put("status", message.getStatus());
            messageData.put("createdTime", message.getCreatedTime());

            WebSocketMessage wsMessage = WebSocketMessage.builder()
                    .type("FRIEND_MESSAGE")
                    .data(messageData)
                    .build();
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(wsMessage)));
        }
    }

    public void sendFriendStatusUpdate(Long targetUserId, Long friendId, boolean isOnline, String lastLoginTime) {
        Channel channel = userChannels.get(targetUserId);
        if (channel != null && channel.isActive()) {
            Map<String, Object> data = new ConcurrentHashMap<>();
            data.put("userId", friendId);
            data.put("isOnline", isOnline);
            data.put("lastLoginTime", lastLoginTime);
            
            WebSocketMessage message = WebSocketMessage.builder()
                    .type("FRIEND_STATUS_UPDATE")
                    .data(data)
                    .build();
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(message)));
        }
    }
}